<template>
    <page-layout>
        <template v-slot:header>
            <el-button @click="saveEvt" size="small" type="primary">保存</el-button>
            <el-button size="small" type="success">取消</el-button>
        </template>
        <el-form :model="page" 
                 :rules="rules" 
                 ref="ruleForm" 
                 label-width="100px"
                 size="mini"
                 >
           <el-row>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                 <el-form-item label="产品名字" prop="name">
                    <el-input  v-model="page.name"></el-input>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                 <el-form-item label="产品状态" prop="state">
                    <el-input class="productState" value="新建" readonly></el-input>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                 <el-form-item  label="成本价" prop="pure_price">
                    <el-input type="number" v-model="page.pure_price"></el-input>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                 <el-form-item label="售价" prop="price">
                    <el-input type="number" v-model="page.price"></el-input>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                 <el-form-item label="优惠" prop="discount">
                    <el-input type="number" v-model="page.discount"></el-input>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                 <el-form-item label="限购" prop="limit">
                    <el-input type="number" v-model="page.limit"></el-input>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                 <el-form-item label="上架时间" prop="sale_stime">
                    <el-date-picker
                        v-model="page.sale_stime"
                        align="right"
                        type="date"
                        placeholder="选择上架日期"
                        :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                 <el-form-item label="下架时间" prop="sale_etime">
                    <el-date-picker
                        v-model="page.sale_etime"
                        align="right"
                        type="date"
                        placeholder="选择下架日期"
                        :picker-options="pickerOptionTwo">
                    </el-date-picker>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                 <el-form-item label="类型" prop="type">
                    <el-select v-model="page.type"  placeholder="选择类型">
                        <el-option
                        v-for="item in options.type"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                 <el-form-item label="单位" prop="unit">
                    <el-select v-model="page.unit"  placeholder="选择类型">
                        <el-option
                        v-for="item in options.unit"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                 <el-form-item label="品级" prop="level">
                    <el-select v-model="page.level"  placeholder="选择类型">
                        <el-option
                        v-for="item in options.level"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                 <el-form-item label="产地" prop="place">
                    <el-input  v-model="page.place"></el-input>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                 <el-form-item label="品牌" prop="brand">
                    <el-input  v-model="page.brand"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="24" >
                 <el-form-item label="详情" prop="detail">
                    <el-tag style="margin: 0 10px 10px 0;"
                     v-for="tag in page.detail"
                      :key="tag" 
                      @close="closeEvt(tag,'detail')"
                      closable>
                        {{tag}}
                    </el-tag>
                    <el-button @click="fileAddEvt('detail')" size="small" icon="el-icon-folder-add"></el-button>
                </el-form-item>
            </el-col>
            <el-col :span="24" >
                 <el-form-item label="banner" prop="banner">
                    <el-tag style="margin: 0 10px 10px 0;"
                     v-for="tag in page.banner"
                      :key="tag" 
                      @close="closeEvt(tag,'banner')"
                      closable>
                        {{tag}}
                    </el-tag>
                    <el-button @click="fileAddEvt('banner')" size="small" icon="el-icon-folder-add"></el-button>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                 <el-form-item label="备注" prop="remark">
                    <el-input  v-model="page.remark"></el-input>
                </el-form-item>
            </el-col>
            <MyList v-model="page.list" />
           </el-row>
        </el-form>
    </page-layout>
</template>
<script>
import { dictListApi, fileUploadApi, productSaveApi } from '@/apis/productApi'
import { filePicker } from '@/util'
import MyList from './MyList.vue'
export default {
    components:{
        MyList
    },
    data() {
        return {
            page:{
                "list": [],
                "name": "",
                "state": "new",
                "pure_price": 0,
                "price": 0,
                "discount": 0,
                "limit": 0,
                "sale_stime": "",
                "sale_etime": "",
                "type": "",
                "unit": "",
                "level": "",
                "place": "",
                "brand": "",
                "detail": [],
                "banner": [],
                "remark": ""
            },
            pickerOptions:{
                disabledDate:(time) =>{
                    // debugger
                    // console.log(this)
                    if(time){
                        // console.log(time.getTime())
                        if(this.page.sale_etime){
                            return time.getTime() > this.page.sale_etime.getTime()-24*60*60*1000 
                        }
                        else{
                            return time.getTime()+0 < Date.now()-24*60*60*1000
                        }
                    }
                    else{
                        return time.getTime() < Date.now()-24*60*60*1000
                    }
            },
            shortcuts: [{
                text: '今天',
                onClick(picker) {
                picker.$emit('pick', new Date());
                }
            }, {
                text: '昨天',
                onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24);
                picker.$emit('pick', date);
                }
            }, {
                text: '一周前',
                onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', date);
                }
            }]
            },
            pickerOptionTwo:{
                disabledDate:(times)=>{
                    // debugger
                    // console.log(times.getTime())
                    // console.log(new Date(this.page.sale_stime).getTime())
                    if(times){
                        if(this.page.sale_stime){
                        return times.getTime() < this.page.sale_stime.getTime()+24*60*60*1000
                        }
                        else{
                        return times.getTime() < Date.now()+24*60*60*1000
                        }
                    }
                    else{
                        return times.getTime() < Date.now()+24*60*60*1000
                    }
            },
            shortcuts: [{
                text: '今天',
                onClick(picker) {
                picker.$emit('pick', new Date());
                }
            }, {
                text: '昨天',
                onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24);
                picker.$emit('pick', date);
                }
            }, {
                text: '一周前',
                onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', date);
                }
            }]
            },
            rules:{
                name:[
                    {required:true,message:'产品名字必填'}
                ],
                pure_price:[
                    {required:true,message:'成本价必填'},
                    {validator:(_, value, callback)=>{ 
                        if (value/1 > this.page.price/1) {
                            callback(new Error('成本价不能高于售价'));
                        } 
                        else if(value===0){
                            callback(new Error('成本价不能为0'))
                        }
                        else {
                        callback();
                        }
                    }}
                ],
                price:[
                    {required:true,message:'售价必填'},
                    {validator:(_, value, callback)=>{ 
                        if (value/1 < this.page.pure_price/1) {
                        callback(new Error('售价不能低于售价'));
                        } 
                        else if(value===0){
                            callback(new Error('售价不能为0'))
                        }
                        else {
                            callback();
                        }
                    }}
                ],
                sale_stime:[
                    {required:true,message:'上架时间必填'},
                    {validator:(_,val,callback)=>{
                        if (val.getTime()< Date.now()-24*60*60*1000) {
                        callback(new Error('上架时间不能早于今天'));
                        } else {
                            callback();
                        }
                    }}
                ],
                sale_etime:[
                    {required:true,message:'下架时间必填'},
                    // {validator:(_,val,callback)=>{
                    //     if (val.getTime()< this.page.sale_stime.getTime()) {
                    //     callback(new Error('下架时间不能早于上架时间'));
                    //     } else {
                    //         callback();
                    //     }
                    // }}
                    //这个提醒没必要，因为已经设置了日期禁用状态
                ],
                discount:[
                    {required:true,message:'优惠必填'}
                ],
                limit:[
                    {required:true,message:'限购必填'},
                    {validator:(_,val,callback)=>{
                        if (val< 1) {
                        callback(new Error('限购至少为1件'));
                        } else {
                            callback();
                        }
                    }}
                ],
                type:[
                    {required:true,message:'类型必选'}
                ],
                unit:[
                    {required:true,message:'单位必选'}
                ],
                level:[
                    {required:true,message:'品级必选'}
                ],
                place:[
                    {required:true,message:'产地必填'}
                ],
                brand:[
                    {required:true,message:'品牌必填'}
                ],
                // detail:[
                //     {required:true,message:'详情图必选'}
                // ],
                // banner:[
                //     {required:true,message:'banner图必选'}
                // ],
                remark:[
                    {required:true,message:'备注必填'}
                ],
            },
            options:{
                level:[],
                unit:[],
                type:[]
            }
        }
    },
    methods:{
        saveEvt(){
            // console.log(JSON.stringify(this.page))
            console.log(this.page)
            // this.$refs.ruleForm.validate(function(isPass,rejectFailed){
            //     console.log(isPass,rejectFailed)
            // })
            this.$refs.ruleForm.validate().then(()=>{
                console.log('校验成功')
                // productSaveApi(this.page).then(d=>{
                //     console.log(d)
                // }).catch(e=>{
                //     console.log(e)
                // })
            }).catch(()=>{
                console.log('校验失败')
            })
            this.alertEvt('count',0,'数量',0)
            setTimeout(()=>{
                this.alertEvt('supplier_name','','厂商','空')
            })
            if(this.page.list.length===0){
                this.$message({
                    message:`成分数据不能为空`,
                    type: 'warning',
                    center:true,
                    customClass:'alert-reason',
                    duration:1000
                    });
                    return 
            }
        },
        alertEvt(va,res,prop,none){
            if(va==='count'){
                for (let i= 0; i < this.page.list.length; i++) {
                if(this.page.list[i][va]-res<=0){
                    this.$message({
                    message:`${this.page.list[i].name}的${prop}不能小于${none}`,
                    type: 'warning',
                    center:true,
                    customClass:'alert-reason',
                    duration:1500
                    });
                    return
                }
            }
            }
            for (let i= 0; i < this.page.list.length; i++) {
                if(this.page.list[i][va]===res){
                    this.$message({
                    message:`${this.page.list[i].name}的${prop}不能为${none}`,
                    type: 'warning',
                    center:true,
                    customClass:'alert-reason',
                    duration:1500
                    });
                    return
                }
            }
        },
        closeEvt(tag,type){
            // console.log(tag)
            this.page[type]=this.page[type].filter(it =>it!==tag)
        },
        fileAddEvt(type){
            filePicker(files=>{
                    // console.log(files)
                    let formData = new FormData()
                    Array(files.length).fill().forEach((_,i)=>{
                        formData.append('file',files[i])
                    })
                    fileUploadApi('product_'+type,formData).then(d =>{
                        // console.log(d)
                        if(d.code===200){
                            this.page[type] = this.page[type].concat(
                                d.data.map(it=>it.path)
                            )
                            // console.log(d)
                        }
                    })
                })
        }
    },
    mounted(){
        Promise.all([
            dictListApi('UNITS'),
            dictListApi('MEDICAL'),
            dictListApi('PRODUCT_LEVEL')
        ]).then(([unit,medical,productlevel])=>{
            // console.log(unit,medical,productlevel)
            if(unit.code===200){
                this.options.unit=unit.data.rows
            }
            if(medical.code===200){
                this.options.type=medical.data.rows
            }
            if(productlevel.code===200){
                this.options.level=productlevel.data.rows
            }
            // console.log(this.options)
        })
    }
}
</script>
<style lang="less" >
   .productState{ 
        .el-input__inner{
            text-align: center !important;
        }
    }
    .alert-reason{
        height: 5vh;
        min-width: 210px !important;
    }
</style>